package com.xuecheng.content.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectList;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TeachplanServiceImpl  implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;

    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;


    @Override
    public List<TeachplanDto> findTeachplamnTree(Long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        //通过课程计划id 判断是新增还是修改
        Long teachplanDtoId = saveTeachplanDto.getId();
        if (teachplanDtoId==null){
            //新增
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            //确定排序字段 找到他的同级节点个数  排序字段就是个数加1
            Long parentid = saveTeachplanDto.getParentid();
            Long courseId = saveTeachplanDto.getCourseId();
            int teachplanCount = getMaxOrder(courseId, parentid);
            teachplan.setOrderby(teachplanCount);

            teachplanMapper.insert(teachplan);
        }else{
            //修改
            Teachplan teachplan = teachplanMapper.selectById(teachplanDtoId);
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }
    }

    @Override
    public void deleteTeachplan(Long teachplanId) {
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan.getGrade().equals(1)){
            //删除的为一级节点  查询有没有下面的小节
            LambdaQueryWrapper<Teachplan> queryWrapper =
                    new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getParentid, teachplanId);
            Integer count = teachplanMapper.selectCount(queryWrapper);
            if(count>0){
                XueChengPlusException.cast("课程章节存在子章节，无法删除");
            }
            int res = teachplanMapper.deleteById(teachplanId);
            if(res<=0){
                XueChengPlusException.cast("删除课程计划失败");
            }
        }else {
            //删除的为二级节点
            teachplanMapper.deleteById(teachplanId);
            //删除相关媒资信息
            LambdaQueryWrapper<TeachplanMedia> mediaLambdaQueryWrapper
                    = new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, teachplanId);
            TeachplanMedia teachplanMedia = teachplanMediaMapper.selectOne(mediaLambdaQueryWrapper);
            if(teachplanMedia==null){
                //没有相关媒资信息 直接结束
                return ;
            }
            teachplanMediaMapper.deleteById(teachplanMedia);
        }
    }

    @Override
    public void moveTeachplan(Long teachplanId, String moveType) {
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teachplan::getParentid,teachplan.getParentid())
                .eq(Teachplan::getCourseId,teachplan.getCourseId());
        if("down".equals(moveType)){
            wrapper.gt(Teachplan::getOrderby,teachplan.getOrderby()).orderByAsc(Teachplan::getOrderby);
        }else{
            wrapper.lt(Teachplan::getOrderby,teachplan.getOrderby()).orderByDesc(Teachplan::getOrderby);
        }
        List<Teachplan> selectList = teachplanMapper.selectList(wrapper);

        if(selectList!=null && !selectList.isEmpty()){
            Teachplan otherTeachplan = selectList.get(0);
            //互换位置
            Integer currentOrderBy = teachplan.getOrderby();
            teachplan.setOrderby(otherTeachplan.getOrderby());
            otherTeachplan.setOrderby(currentOrderBy);
            teachplanMapper.updateById(teachplan);
            teachplanMapper.updateById(otherTeachplan);
        }
        else{
            if("down".equals(moveType)){
                XueChengPlusException.cast("当前排序已经是最后一个了");
            }else{
                XueChengPlusException.cast("当前排序已经是第一个了");
            }
        }
    }


    @Transactional
    @Override
    public void associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {

        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }



        //删除原有记录    根据课程计划id 删除它所绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,bindTeachplanMediaDto.getTeachplanId()));


        //添加新记录
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtils.copyProperties(bindTeachplanMediaDto,teachplanMedia);
        teachplanMedia.setCourseId(teachplan.getCourseId());
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
    }


    /**
     * @description 获取最新的排序号
     * @param courseId  课程id
     * @param parentId  父课程计划id
     * @return int 最新排序号
     */
    private int getTeachplanCount(long courseId,Long parentId){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.eq(Teachplan::getParentid,parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count+1;
    }

    /*获取子章节中的最大排序号，设置新的排序号，如果没有，啧默认从1开始
    * */
    private  int getMaxOrder(Long courseId, Long parentid){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId)
                .eq(Teachplan::getParentid,parentid)
                .orderByDesc(Teachplan::getOrderby);
        List<Teachplan> selectList = teachplanMapper.selectList(queryWrapper);
        Integer order;
        if(selectList==null || selectList.isEmpty()){
            order=1;
        }else {
            order=selectList.get(0).getOrderby()+1;
        }
        return order;
    }

}
